const titbit = require('titbit');
const pg = require('pg');
const fs=require('fs');
const token = require('titbit-token');
const tbloader = require('titbit-loader');
const dbcfg = require('./dbconfig');
const wxkey = require('./wxkey.js');
const {httpcli} = require('gohttp');
process.chdir(__dirname);

try {
    fs.accessSync('./images')
  } catch (err) {
    fs.mkdirSync('./images')
}

let cert_path = '/usr/local/share';
const app = new titbit({
    debug: true,
    globalLog:true,
    cert: `${cert_path}/api.124ss.xyz.pem`,
    key: `${cert_path}/api.124ss.xyz.key`
})

let psql=new pg.Pool(dbcfg);

let tb = new tbloader({
    homeFile: 'home.js'
});
tb.init(app);


app.addService('psql',psql);

app.addService('imagePath1', `/usr/images`);

app.addService('imagePath', `${__dirname}/images`);


 let tok = new token({
     //token有效期，单位为秒
     expires: 72000,
     //必须是32位字符
     key: '1qaz2wqx32dc4rf750gb6yhn7ujmki89',
     //必须是16位字符
     iv: '1q2r3e41536y7u8i'
})

app.addService('tok', tok);

let usertok = new token({
    //token有效期，单位为秒
    expires: 72000,
    //必须是32位字符
    key: '1qaz2wqx32dc4rf750gb6yhn7uj1ki67',
    //必须是16位字符
    iv: '1q2r3e41536y124i'
})

app.addService('usertok', usertok);

app.options('/', async c => {}, {group: '/'});

app.get('/mp-login/:code', async c => {
    let auth_url = `https://api.weixin.qq.com/sns/jscode2session`
            + `?appid=${wxkey.appid}`
            + `&secret=${wxkey.secret}`
            + `&js_code=${c.param.code}`
            + `&grant_type=authorization_code`
  
    let ret = await httpcli.get(auth_url)
                          .then(res => {
                            return res.json()
                          })
    let sqltext = `INSERT INTO users(open_id)VALUES($1)`;
    r=await c.service.psql.query(sqltext,[ret.openid]);
    if (!ret.openid) return c.status(500).send('授权登录失败，请稍后再试。')
    c.send( {token: usertok.make(ret)});
})

let port_ind = process.argv.indexOf('--port')

let port = 4399;

if (port_ind > 0 && port_ind + 1 < process.argv.length) {
    let self_port = process.argv[port_ind+1];
    if (!isNaN(self_port)) {
        port = parseInt(self_port);
    }
}

app.run(port);
